﻿using MslDiary.BLL;
using MslDiary.Utils;
// 版权所有：2015  All Rights Reserved.
// 文 件 名：LoginWindowViewModel.cs
// 功能描述：
// 创建标识：m.sh.lin0328@163.com 2015/1/2 15:25:02
// 修改描述：
//----------------------------------------------------------------*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
using System.Xml;
using MFW = MslDiary.Framework;

namespace MslDiary.ViewModel
{
    public class LoginWindowViewModel : MslDiary.Framework.ViewModelBase
    {
        private System.Windows.Window win;
        private A_UserBLL userBLL = new A_UserBLL();
        public LoginWindowViewModel()
        {
            MFW.Gloable.LoginSuccessed = false;
            #region 初始化

            this.WindowLoadCommand = new CommandBase((Object window) =>
            {
                if (window != null)
                {
                    this.win = window as System.Windows.Window;
                    this.win.MouseLeftButtonDown += (s, e) =>
                    {
                        if (e.LeftButton == MouseButtonState.Pressed)
                            this.win.DragMove();
                    };
                }
                Load();
            });
            #endregion
            #region 新建日记本

            this.AddDiaryCommand = new CommandBase((Object parameter) =>
            {
                this.IsShowAddDiaryPanel = true;
                this.IsShowLoginPanel = false;
            });
            #endregion
            #region 帐号选择

            this.AccountSelectedChangedCommand = new CommandBase((Object account) =>
            {
                if (account == null || account.ToString().Length == 0) return;
                this.Account = account.ToString();
                if (MFW.Gloable.UserPwdTable != null && MFW.Gloable.UserPwdTable.ContainsKey(account))
                {
                    this.Pwd = MFW.Gloable.UserPwdTable[account].ToString();
                    this.Pwd = MslDiary.Framework.Helper.DecryptDbPwd(account.ToString(), this.Pwd);
                }
                else
                {
                    this.Pwd = "";
                }
                if (String.IsNullOrEmpty(this.Pwd))
                    this.IsSavePwd = false;
            });
            #endregion
            #region 登录

            this.LoginAcceptCommand = new CommandBase((Object url) => Login());
            this.LoginEnterCommand = new CommandBase((Object url) =>
            {
                if (String.IsNullOrEmpty(this.Pwd)) return;
                Login();
            });
            #endregion

            this.AddDiaryAcceptCommand = new CommandBase((Object window) =>
            {
                if (window == null)
                    return;
                this.win = (System.Windows.Window)window;
                AddDiary();
            });
            this.CancleAddDiaryCommand = new CommandBase((Object parameter) =>
            {
                this.IsShowAddDiaryPanel = false;
                this.IsShowLoginPanel = true;
            });
            //this.CloseCommand = new CommandBase((Object parameter) => Helper.Instance.ExitApp());
        }

        #region 属性

        private string _loddingInfo = "准备就绪...";
        private string _pwd;
        private bool _savePwd = false;
        private string _account;
        private List<string> _accountList = new List<string>();
        private bool _isShowLoginPanel = true;
        private bool _isShowAddDiaryPanel = false;
        private string _diaryAccount;
        private string _nickName;
        private string _dbPwd;
        public string DiaryAccount
        {
            get { return _diaryAccount; }
            set
            {
                // base.SetProperty<string>(ref this._account, value);
                if (this._diaryAccount == value)
                    return;
                this._diaryAccount = value;
                this.RaisePropertyChanged("DiaryAccount");
            }
        }
        public string NickName
        {
            get { return _nickName; }
            set
            {
                //base.SetProperty<string>(ref this._nickName, value);
                if (this._nickName == value)
                    return;
                this._nickName = value;
                this.RaisePropertyChanged("NickName");
            }
        }
        public string DataBasePwd
        {
            get { return _dbPwd; }
            set
            {
                //base.SetProperty<string>(ref this._dbPwd, value);
                if (this._dbPwd == value)
                    return;
                this._dbPwd = value;
                this.RaisePropertyChanged("DataBasePwd");
            }
        }
        /// <summary>是否显示登录面板</summary>
        public bool IsShowLoginPanel
        {
            get { return _isShowLoginPanel; }
            set
            {
                if (this._isShowLoginPanel == value)
                    return;
                this._isShowLoginPanel = value;
                this.RaisePropertyChanged("IsShowLoginPanel");
            }
        }
        /// <summary>是否显示创建日记本面板</summary>
        public bool IsShowAddDiaryPanel
        {
            get { return _isShowAddDiaryPanel; }
            set
            {
                if (this._isShowAddDiaryPanel == value)
                    return;
                this._isShowAddDiaryPanel = value;
                this.RaisePropertyChanged("IsShowAddDiaryPanel");
            }
        }
        /// <summary>是否保存密码</summary>
        public bool IsSavePwd
        {
            get { return _savePwd; }
            set
            {
                //base.SetProperty<bool>(ref this._savePwd, value);
                if (this._savePwd == value)
                    return;
                this._savePwd = value;
                this.RaisePropertyChanged("IsSavePwd");
            }
        }
        /// <summary>密码</summary>
        public string Pwd
        {
            get { return _pwd; }
            set
            {
                //base.SetProperty<string>(ref this._pwd, value);
                if (this._pwd == value)
                    return;
                this._pwd = value;
                this.RaisePropertyChanged("Pwd");
            }
        }
        /// <summary>用户名</summary>
        public string Account
        {
            get { return _account; }
            set
            {
                //base.SetProperty<string>(ref this._account, value);
                if (this._account == value)
                    return;
                this._account = value;
                this.RaisePropertyChanged("Account");
            }
        }
        /// <summary>加载信息</summary>
        public string LoadingInfo
        {
            get { return _loddingInfo; }
            set
            {
                //base.SetProperty<string>(ref this._loddingInfo, value);
                if (this._loddingInfo == value)
                    return;
                this._loddingInfo = value;
                this.RaisePropertyChanged("LoadingInfo");
            }
        }
        public List<string> AccountList
        {
            get { return _accountList; }
            set
            {
                //base.SetProperty<List<string>>(ref this._accountList, value);
                if (this._accountList == value)
                    return;
                this._accountList = value;
                this.RaisePropertyChanged("AccountList");
            }
        }
        #endregion

        #region 命令
        /// <summary>保存</summary>
        public ICommand AddDiaryAcceptCommand { get; set; }
        /// <summary>取消</summary>
        public ICommand CancleAddDiaryCommand { get; set; }
        /// <summary> 登录</summary>
        public ICommand LoginAcceptCommand { get; set; }
        /// <summary>新建日记本</summary>
        public ICommand AddDiaryCommand { get; set; }
        /// <summary> 登录</summary>
        public ICommand LoginEnterCommand { get; set; }
        //public ICommand CloseCommand { get; set; }
        public ICommand WindowLoadCommand { get; set; }
        public ICommand AccountSelectedChangedCommand { get; set; }
        #endregion

        #region 方法

        public void AddDiary()
        {
            if (String.IsNullOrEmpty(this.DiaryAccount))
            {
                MslDiary.Utils.Helper.Instance.AlertWarning("登录名不能为空！");
                return;
            }
            if (String.IsNullOrEmpty(this.DataBasePwd))
            {
                MslDiary.Utils.Helper.Instance.AlertWarning("登录密码不能为空！");
                return;
            }
            this.DiaryAccount = this.DiaryAccount.Trim();
            this.DataBasePwd = this.DataBasePwd.Trim();
            if (this.DiaryAccount.Length < 4 || this.DiaryAccount.Length > 18)
            {
                MslDiary.Utils.Helper.Instance.AlertWarning("登录名长度为 4~18 位！");
                return;
            }
            if (String.IsNullOrEmpty(this.DataBasePwd))
            {
                MslDiary.Utils.Helper.Instance.AlertWarning("登录密码不能为空！");
                return;
            }
            if (this.DiaryAccount.Length > 18)
            {
                MslDiary.Utils.Helper.Instance.AlertWarning("登录密码长度不能大于 18 位！");
                return;
            }
            string msg = String.Empty;
            bool isOk = this.userBLL.AddDiary(this.DiaryAccount, this.NickName, this.DataBasePwd, out msg);
            if (isOk)
            {
                MslDiary.Utils.Helper.Instance.AlertSuccess("恭喜您，您的日记本已创建成功！");
                this.IsShowAddDiaryPanel = false;
                this.IsShowLoginPanel = true;
            }
            else
            {
                MslDiary.Utils.Helper.Instance.AlertWarning(msg);
            }
        }
        private void Load()
        {
            #region 加载账号

            List<string> list = MSL.Tool.IOHelper.Instance.GetAllFiles(MFW.Gloable.StartPath + "\\data\\", new string[] { ".xml" });
            if (list == null || list.Count == 0)
            {
                MslDiary.Utils.Helper.Instance.AlertError("配置文件丢失，无法登录！");
                return;
            }
            this.AccountList = new List<string>();
            foreach (string item in list)
            {
                if (item.Contains("user.xml")) continue;

                string tmp = item.Split('_')[0];//用户名中不能存在 _ .
                this.AccountList.Add(tmp);
            }
            #endregion

            string path = MFW.Gloable.StartPath + "\\data\\user.xml";
            MFW.IO.ConfigHelper config = new MFW.IO.ConfigHelper(path);
            MFW.Gloable.UserPwdTable = new Hashtable();
            XmlNode node = config.GetNodeByKey(MFW.IO.ConfigHelper.ROOT_NODE + "/User");
            object pwd;
            for (int k = 0; k < node.ChildNodes.Count; k++)
            {
                XmlNode v = node.ChildNodes[k];
                MFW.Gloable.UserPwdTable.Add(v.Attributes["account"].Value, v.Attributes["pwd"].Value);
                if (String.IsNullOrEmpty(this.Pwd))
                {
                    this.Account = v.Attributes["account"].Value;
                    pwd = MFW.Gloable.UserPwdTable[this.Account];
                    if (pwd != null && pwd.ToString().Length > 0)
                    {
                        this.IsSavePwd = true;
                        this.Pwd = pwd.ToString();
                        this.Pwd = MslDiary.Framework.Helper.DecryptDbPwd(this.Account, this.Pwd);
                    }
                }
            }
            node = config.GetNodeByKey("User");
        }
        //系统初始化
        private void Login()
        {
            MSL.Tool.LogHelper.LogPath = MFW.Gloable.StartPath + "\\log\\";
            MSL.Tool.IOHelper.Instance.CreateFolder(MSL.Tool.LogHelper.LogPath);
            MSL.Tool.IOHelper.Instance.DeleteFiles(MSL.Tool.LogHelper.LogPath, new string[] { ".txt", ".log" }, 4);//删除4天前日志文件
            try
            {
                this.LoadingInfo = "正在登录...";
                if (String.IsNullOrEmpty(this.Pwd))
                {
                    MslDiary.Utils.Helper.Instance.AlertWarning("密码不能为空！");
                    return;
                }
                this.LoadingInfo = "加载配置...";
                MFW.Gloable.Config = MFW.Gloable.StartPath + "\\data\\" + this.Account + "_config.xml";
                if (!File.Exists(MFW.Gloable.Config))
                {
                    MslDiary.Utils.Helper.Instance.AlertError("该用户不存在！");
                    return;
                }
                MFW.IO.ConfigHelper config = new MFW.IO.ConfigHelper(MFW.Gloable.Config);

                #region 文件存在

                if (!System.IO.File.Exists(MFW.Gloable.Config))
                {
                    MslDiary.Utils.Helper.Instance.AlertError("配置文件丢失,无法登录！");
                    Application.Current.Shutdown();
                    //MessageBox.Show("警告", "配置文件丢失！", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                if (!System.IO.File.Exists(MFW.Gloable.StartPath + "\\data\\" + this.Account + "_db.db"))
                {
                    MslDiary.Utils.Helper.Instance.AlertError("数据库文件丢失！");
                    Application.Current.Shutdown();
                    return;
                }
                #endregion

                //保存登录信息到文件 user.xml
                this.userBLL.SaveLoginUserConfig(this.Account, this.Pwd, this.IsSavePwd);

                #region 数据库配置 SQLite

                this.LoadingInfo = "加载数据库配置...";

                string conn = config.GetValueByKey("Conn");
                string msg = String.Empty;

                if (!this.userBLL.Login(conn, this.Account, this.Pwd, out msg))
                {
                    this.LoadingInfo = msg;
                    return;
                }
                #endregion
                //清空没有保存的图片
                new A_AnnexBLL().DeleteTmpContentImage();

                #region 读取配置

                this.LoadingInfo = "读取配置文件信息...";
                Helper.Instance.ReadConfig();
                #endregion

                MSL.Tool.IOHelper.Instance.CreateFolder(MslDiary.Framework.Gloable.CachePath);//清空缓存
                MSL.Tool.IOHelper.Instance.CreateFolder(MslDiary.Framework.Gloable.CachePath + "0\\");//日记没有添加成功时的图片临时目录

                NotifyIconHelper.Instance();
                NotifyIconHelper.Instance().ShowBalloonTip("提示", "程序运行成功！");

                MFW.Gloable.LoginSuccessed = true;
                this.win.Close();
            }
            catch (Exception ex)
            {
                MSL.Tool.LogHelper.Instance.WriteLog(ex.ToString());
            }
        }
        #endregion
    }
}
